package org.ldx.lotterysystem.controller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.ldx.lotterysystem.common.pojo.CommonResult;
import org.ldx.lotterysystem.common.utils.JacksonUtil;
import org.ldx.lotterysystem.controller.param.DrawPrizeParam;
import org.ldx.lotterysystem.controller.param.ShowWinningRecordsParam;
import org.ldx.lotterysystem.controller.result.WinningRecordResult;
import org.ldx.lotterysystem.service.DrawPrizeService;
import org.ldx.lotterysystem.service.dto.WinningRecordDTO;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class DrawPrizeController {
    @Resource
    DrawPrizeService drawPrizeService;
    /**
     * 作为rabbitmq生成者
     * 只做：1.发送消息给消费者 2.返回值.
     * 异步进行 保证抽奖的时效性。
     * @param param
     * @return
     */
    @RequestMapping("/draw-prize")
    public CommonResult<Boolean> drawPrize(@Validated @RequestBody DrawPrizeParam param){
        log.info("drawPrize DrawPrizeParam:{}", JacksonUtil.writeValueAsString(param));
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }
    @RequestMapping("/winning-records/show")
    public CommonResult<List<WinningRecordResult>> showWinningRecord(@Validated @RequestBody ShowWinningRecordsParam param){
        log.info("showWinningRecord DrawPrizeParam{}",JacksonUtil.writeValueAsString(param));
        List<WinningRecordDTO> winningRecordDTOList = drawPrizeService.getRecords(param);
        return CommonResult.success(convertToWinningRecordResult(winningRecordDTOList));
    }

    private List<WinningRecordResult> convertToWinningRecordResult(List<WinningRecordDTO> winningRecordDTOList) {
        if(CollectionUtils.isEmpty(winningRecordDTOList)){
            return Arrays.asList();
        }
        return winningRecordDTOList.stream()
                .map(winningRecordDTO -> {
                    WinningRecordResult result = new WinningRecordResult();
                    result.setWinnerId(winningRecordDTO.getWinnerId());
                    result.setWinnerName(winningRecordDTO.getWinnerName());
                    result.setPrizeName(winningRecordDTO.getPrizeName());
                    result.setPrizeTier(winningRecordDTO.getPrizeTier().name());
                    result.setWinningTime(winningRecordDTO.getWinningTime());
                    return result;
                }).collect(Collectors.toList());
    }
}
